package com.celesea.configuration.sso;

import com.celesea.configuration.ehcache.EhcacheProvider;
import com.celesea.configuration.security.CasRedisProvider;
import com.celesea.framework.authority.AuthorityPrincipal;
import com.celesea.framework.jwt.JwtUserDetailService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

import java.util.concurrent.TimeUnit;

@Component
public class RedisUserDetailsService implements JwtUserDetailService {

    private static Logger logger = LoggerFactory.getLogger(RedisUserDetailsService.class);

    private static final String LOGIN_SESSION_ID = "loginSessioinId";
    private static final String BRAND_ID = "brandId";
    private static final String SHOP_ID = "shopId";
    private static final String USER_ID = "userId";

    @Autowired
    private CasRedisProvider casRedisProvider;

    @Autowired
    private EhcacheProvider ehcacheProvider;

    @Override
    public AuthorityPrincipal loadUserDetails(String loginSessionId) throws UsernameNotFoundException {
        AuthorityPrincipal userDetails = ehcacheProvider.getUserDetailsFromCache(loginSessionId);
        if (userDetails == null) {
            userDetails = casRedisProvider.getUserInfoFromRedis(loginSessionId);
            Assert.notNull(userDetails,"获取用户登录信息失败："+loginSessionId);
            ehcacheProvider.cacheUserDetails(loginSessionId,userDetails);
            ehcacheProvider.cacheUserTimeStamp(loginSessionId);
        }
        return userDetails;
    }

    /**
     * 更新用户的有效期
     *
     * @param loginSessionId
     * @param maxAge
     * @param timeUnit
     */
    @Override
    public void updateExpire(String loginSessionId, Integer maxAge, TimeUnit timeUnit) {
        casRedisProvider.updateExpire(loginSessionId,maxAge,timeUnit);
    }
}
